package com.yneusoft.pctask.inteceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yneusoft.common.handler.MyException;
import com.yneusoft.pctask.controller.LoginManageController;
import com.yneusoft.pctask.service.LoginManageService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description： 员工管理自定义拦截器
 * @Author: wbf
 * @Date: 2021/11/24 9:31
 */
public class StaffManageInterceptor implements HandlerInterceptor {
    /**
     * 拦截请求，访问controller之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 放行option请求
         */
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        //获取前端传来的token
        String getToken = request.getHeader("token");
        if(getToken == null) {
            throw new MyException("登录异常！请重新登陆！");
        }
        //获取登录板块传来的token
        String realToken = LoginManageService.getToken();
        /**
         * 确定解码密钥
         */
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("token!Q@W3e4r")).build();

        /**
         * 对获取到的token校验
         */
        jwtVerifier.verify(getToken);
        /**
         * 验证token是否相同
         */
        if(getToken.equals(realToken)) return true;
        else {
            throw new MyException("登录异常！请重新登陆！");
        }

    }
}
